package com.deekian.tools.bluetoothtrigger.second;

import android.content.Context;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.deekian.tools.bluetoothtrigger.R;
import com.deekian.tools.bluetoothtrigger.model.WifiHotspotInfo;
import com.deekian.tools.bluetoothtrigger.utils.SharedPreferencesTools;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class SettingActivity extends AppCompatActivity {

    //wifi信息框是否处于可编辑状态
    public static boolean wifi_hot_is_edit = false;

    //展示列表
    ListView list_selected_device;
    //选择列表
    Spinner spinner_select;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        //获取已存蓝牙设备列表展示view对象
        list_selected_device = findViewById(R.id.list_selected_device);
        //获取系统已配对蓝牙设备选择view对象
        spinner_select = findViewById(R.id.spinner_select);

        //添加按钮
        Button add_selected_button = findViewById(R.id.add_selected);

        //编辑热点信息按钮
        Button edit_host_info = findViewById(R.id.edit_host_info);


        //设置标题栏(toolbar)与返回按钮
        android.support.v7.widget.Toolbar toolbar = findViewById(R.id.toolbar);

        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);

        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SettingActivity.this.finish();
            }
        });

        updateWifiHotspotInfoToView();

        //编辑热点信息按钮被点击事件
        edit_host_info.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                EditText in_hotspot_name = findViewById(R.id.in_hotspot_name);
                EditText in_hotspot_password = findViewById(R.id.in_hotspot_password);

                if (wifi_hot_is_edit) {
                    wifi_hot_is_edit = false;
                    view.setBackground(getDrawable(R.drawable.locked));
                    in_hotspot_name.setEnabled(false);
                    in_hotspot_password.setEnabled(false);

                    //保存WIFI热点信息
                    SharedPreferencesTools.updateWifiHotspotInfo(getApplicationContext(), new WifiHotspotInfo(
                            in_hotspot_name.getText().toString(),
                            in_hotspot_password.getText().toString()
                    ));
                } else {
                    wifi_hot_is_edit = true;
                    view.setBackground(getDrawable(R.drawable.unlock));
                    in_hotspot_name.setEnabled(true);
                    in_hotspot_password.setEnabled(true);
                    in_hotspot_name.setFocusableInTouchMode(true);
                    in_hotspot_name.requestFocus();
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.showSoftInput(in_hotspot_name, 0);

                }
            }
        });

        //添加按钮点击事件
        add_selected_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Object _tmpOption = spinner_select.getSelectedItem();
                if (_tmpOption != null) {
                    SpinnerOption spinnerOption = (SpinnerOption) _tmpOption;

                    SharedPreferencesTools.addBluetoothDevice(getApplicationContext(), spinnerOption);

                    updateSelectedDeviceList();
                    updateSpinnerSelect();
                }
            }
        });

        updateSelectedDeviceList();
        updateSpinnerSelect();
    }

    //将已存储的WIFI信息展示到页面上
    private void updateWifiHotspotInfoToView() {
        EditText in_hotspot_name = findViewById(R.id.in_hotspot_name);
        EditText in_hotspot_password = findViewById(R.id.in_hotspot_password);
        WifiHotspotInfo info = SharedPreferencesTools.getWIFIWifiHotspotInfo(getApplicationContext());
        in_hotspot_name.setText(info.getHostname());
        in_hotspot_password.setText(info.getPassword());
    }

    //更新选择框
    public void updateSpinnerSelect() {

        JSONArray cache = SharedPreferencesTools.getCacheBluetoothDeviceArray(getApplicationContext());
        JSONArray system = SharedPreferencesTools.getSystemBluetoothDeviceArray();

        List<String> cacheAddress = new ArrayList<>();

        for (int i = 0; i < cache.length(); i++) {
            try {
                cacheAddress.add(cache.getJSONObject(i).getString("address"));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        List<SpinnerOption> spinnerOptionList = new ArrayList<>();

        for (int i = 0; i < system.length(); i++) {
            try {
                JSONObject devices = system.getJSONObject(i);
                if (!cacheAddress.contains(devices.getString("address"))) {
                    String name = devices.getString("name");
                    String address = devices.getString("address");
                    spinnerOptionList.add(new SpinnerOption(name, address, name + "[" + address + "]"));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        //设置Adapter
        ArrayAdapter<SpinnerOption> townAdapter = new ArrayAdapter<SpinnerOption>(SettingActivity.this, R.layout.support_simple_spinner_dropdown_item, spinnerOptionList);
        townAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner_select.setAdapter(townAdapter);
    }

    //取出已存储的数据进行展示
    public void updateSelectedDeviceList() {
        list_selected_device.setAdapter(new ListViewAdapter(SharedPreferencesTools.getCacheBluetoothDeviceArray(getApplicationContext())));
    }

    /**
     * 要用用于生成显示数据
     *
     * @author huangbq
     */
    class ListViewAdapter extends BaseAdapter {
        JSONArray dataArr;

        public ListViewAdapter(JSONArray dataArr) {
            this.dataArr = dataArr;
        }

        public int getCount() {
            return dataArr.length();
        }

        public Object getItem(int pos) {
            return pos;
        }

        public long getItemId(int pos) {
            return pos;
        }

        public View getView(int pos, View v, ViewGroup p) {
            String show_txt = "设备名: %NAME%\n设备ID: %ADDRESS%";
            try {
                JSONObject line_data = dataArr.getJSONObject(pos);
                show_txt = show_txt.replace("%NAME%", line_data.optString("name", "[error!]"));
                show_txt = show_txt.replace("%ADDRESS%", line_data.optString("address", "[error!]"));
            } catch (JSONException e) {
                e.printStackTrace();
            }
            RelativeLayout relativeLayout = new RelativeLayout(SettingActivity.this);
//            linearLayout.setOrientation(LinearLayout.HORIZONTAL);
            TextView textView = new TextView(SettingActivity.this);
            textView.setText(show_txt);
            textView.setTextSize(15);

            RelativeLayout.LayoutParams textParam = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
            textParam.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
            textParam.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);


            Button button = new Button(SettingActivity.this);
            button.setId(pos);
//            button.setBackground(getDrawable(R.drawable.delete));
            button.setText("删除");
            button.setTextColor(Color.RED);

            RelativeLayout.LayoutParams btnParam = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
            btnParam.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
            btnParam.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);


            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    SharedPreferencesTools.deleteBluetoothDevice(getApplicationContext(), view.getId());
                    updateSelectedDeviceList();
                    updateSpinnerSelect();
                }
            });

            relativeLayout.addView(textView, textParam);
            relativeLayout.addView(button, btnParam);

            return relativeLayout;
        }
    }

    public class SpinnerOption {
        private String name = "";
        private String address = "";
        private String text = "";

        private SpinnerOption() {
        }

        public SpinnerOption(String name, String address, String text) {
            this.name = name;
            this.address = address;
            this.text = text;
        }

        @Override
        public String toString() {
            return text;
        }

        public String getBtName() {
            return name;
        }

        public String getAddress() {
            return address;
        }

        public String getText() {
            return text;
        }
    }


}
